import time
import os
import logging
import psutil  # 导入 psutil 库
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from PIL import Image, ImageDraw, ImageFont

# 配置日志
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

# 要监视的目录 (替换为你GUI保存图像的目录)
WATCH_DIRECTORY = "C:\\"

# 目标目录 (根目录)
TARGET_DIRECTORY = r"C:\Users\32280\Desktop\pythonProject2\output" # 当前工作目录

# 图像文件扩展名
IMAGE_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.tiff', '.bmp')

# GUI 进程名称 (替换为你的 GUI 进程名称)
GUI_PROCESS_NAME = "python.exe"  # 或者 "你的GUI程序.exe"

def is_gui_process_running():
    """检查 GUI 进程是否正在运行."""
    for process in psutil.process_iter(['name']):
        if process.info['name'].lower() == GUI_PROCESS_NAME:
            return True
    return False

class ImageEventHandler(FileSystemEventHandler):
    def on_created(self, event):
        if event.is_directory:
            return
        filepath = event.src_path
        filename = os.path.basename(filepath)
        logging.info(f"检测到新文件: {filename}")

        # 忽略以 "watermarked_" 开头的文件
        if filename.startswith("watermarked_"):
            logging.info("忽略 watermarked_ 文件")
            return

        # 检查文件是否是图像
        if filename.lower().endswith(IMAGE_EXTENSIONS):
            try:
                time.sleep(0.5)  # 等待 0.5 秒
                try:
                    image = Image.open(filepath).convert("RGB") # 确保是 RGB 模式
                    image.load() # 强制加载图像数据
                    print(f"成功打开图像: {filepath}, 模式: {image.mode}")
                except Exception as open_error:
                    logging.error(f"无法打开图像 {filepath}: {open_error}")
                    return  # 如果无法打开图像，则直接返回

                watermarked_image = add_text_watermark(image, "Processed by MyGUI")

                # 保存带有水印的图像 (可以保存到新的文件或覆盖原文件)
                watermarked_filepath = os.path.join(TARGET_DIRECTORY, "watermarked_" + filename)
                print(f"保存水印图像到：{watermarked_filepath}")  # 调试信息
                try:
                    watermarked_image.save(watermarked_filepath, "PNG") # 强制使用 PNG 格式
                    logging.info(f"已添加水印并保存为: {watermarked_filepath}")
                except Exception as save_error:
                    logging.error(f"保存水印图像失败: {save_error}")

            except Exception as e:
                logging.error(f"处理文件 {filename} 失败: {e}")

def add_text_watermark(image, text, font_size=50, color=(255, 0, 0, 128), font_path=r"C:\Windows\Fonts\arial.ttf"):  # 修改
    """添加文本水印."""
    try:
        draw = ImageDraw.Draw(image)
        width, height = image.size

        # 尝试加载字体
        try:
            font = ImageFont.truetype(font_path, size=font_size)  # 修改
        except IOError:
            print("无法加载字体，使用默认字体")
            font = ImageFont.load_default()  # 使用默认字体

        # 计算文本大小
        text_width, text_height = draw.textsize(text, font=font)
        print(f"水印文本大小: {text_width}x{text_height}")
        print(f"水印位置: x={width - text_width - 20}, y={height - text_height - 20}")


        # 设置水印位置 (右下角)
        x = width - text_width - 20  # 修改
        y = height - text_height - 20  # 修改

        # 添加文本
        draw.text((x, y), text, font=font, fill=color)
        return image
    except Exception as e:
        print(f"添加文本水印失败: {e}")
        return image

if __name__ == "__main__":
    event_handler = ImageEventHandler()
    observer = Observer()
    observer.schedule(event_handler, WATCH_DIRECTORY, recursive=True)  # recursive=True 监视所有子目录
    observer.start()
    logging.info(f"开始监视目录: {WATCH_DIRECTORY}")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()